-- Contador

library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
use ieee.numeric_std.all;

entity CONTADOR is
	generic
	(
		MIN_COUNT : integer := 0;
		MAX_SEG : integer := 59;
		MAX_MIN : integer := 59;
		MAX_HOR : integer := 23
	);

	port
	(
		CLK, CLR : in std_logic;
		INC_M : in std_logic;
		INC_H : in std_logic;
		LOAD : in std_logic;
		PRESETS : in std_logic_vector(15 downto 0);
		Q_SEG : out std_logic_vector(7 downto 0);
		Q_MIN : out std_logic_vector(7 downto 0);
		Q_HOR : out std_logic_vector(7 downto 0)
	);
end CONTADOR;

architecture DT_FLOW of CONTADOR is
signal TMP_MIN : integer range MIN_COUNT to MAX_MIN := 0;
signal TMP_HOR : integer range MIN_COUNT to MAX_HOR := 0;
signal TMP_PRESETS : std_logic_vector(15 downto 0);

begin

	process(CLK, CLR, INC_M, INC_H, LOAD)
	variable SEG : integer range MIN_COUNT to MAX_SEG := 0;
	variable MIN : integer range MIN_COUNT to MAX_MIN := 0;
	variable HOR : integer range MIN_COUNT to MAX_HOR := 0;
	begin
	
		if (CLR = '0') then
			Q_SEG <= "00000000";
			Q_MIN <= "00000000";
			Q_HOR <= "00000000";
			SEG := 0;
			MIN := 0;
			HOR := 0;
		elsif (CLK'EVENT AND CLK='1') then
			if (INC_M = '0') then
				MIN := MIN + 1;
			elsif (INC_H = '0') then
				HOR := HOR + 1;
			elsif (LOAD = '0') then
				Q_MIN <= PRESETS(7 downto 0);
				Q_HOR <= PRESETS(15 downto 8);
				--TMP_PRESETS <= PRESETS;
				--TMP_MIN <= con_integer(signed(TMP_PRESETS(7 downto 0)));
				--MIN := conv_integer(PRESETS(7 downto 0));
				--HOR := conv_integer(PRESETS(15 downto 8));
			else
				SEG := SEG + 1;
				if (SEG > MAX_SEG) then
					SEG := 0;
					MIN := MIN + 1;
					if (MIN > MAX_MIN) then
						MIN := 0;
						HOR := HOR + 1;
						if (HOR > MAX_HOR) then
							HOR := 0;
						end if;
					end if;
				end if;
			end if;
				
		end if;
		
		
	Q_SEG <= conv_std_logic_vector(SEG, 8);
	Q_MIN <= conv_std_logic_vector(MIN, 8);
	Q_HOR <= conv_std_logic_vector(HOR, 8);
	
	end process;

end DT_FLOW;
